<template>
  <div>
    <el-row>
      <el-col>
        <el-form :inline="true"
                 :model="searchForm"
                 style="margin-left: 30px; margin-top: 20px; width: 80%; float: left">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.name"
                      size="small"></el-input>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="searchForm.status"
                       size="small">
              <el-option label="启用"
                         value="1"></el-option>
              <el-option label="禁用"
                         value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="query"
                       size="small">查询</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary"
                   style="float: right; margin-top: 25px; margin-right: 40px"
                   @click="add"
                   size="small">新增</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-left: 20px">
      <el-table size="small"
                :data="tableData"
                border
                stripe
                style="width: 98%">
        <el-table-column prop="name"
                         label="角色名称"
                         align="center"></el-table-column>
        <el-table-column prop="status"
                         label="状态"
                         align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 1">启用</span>
            <span v-if="scope.row.status == 2">禁用</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right"
                         label="操作"
                         width="240"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="relationMenu(scope.row)">关联菜单</el-button>
            <el-button type="text"
                       size="small"
                       @click="relationPermission(scope.row)">关联权限</el-button>
            <el-button type="text"
                       size="small"
                       @click="edit(scope.row)">编辑</el-button>
            <el-button type="text"
                       size="small"
                       @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 10px"
                     background
                     :page-sizes="[1, 10, 20, 50, 100, 200]"
                     :page-size="pageData.pageSize"
                     layout="prev, pager, next,sizes"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pageData.pageNum"
                     :total="pageData.total"></el-pagination>
    </el-row>

    <!--菜单穿梭框-->
    <el-dialog title="关联菜单"
               :visible.sync="transforDialog"
               width="650px"
               :close-on-click-modal="false">
      <tree-transfer :from_data="menuList"
                     @add-btn="treeAdd"
                     @remove-btn="treeRemove"
                     :title="['全部菜单', '已选菜单']"
                     :to_data="selectedRows"
                     node_key="id"
                     :defaultProps="{ label: 'name', children: 'children' }"
                     pid="parentId"
                     height="500px"
                     filter
                     openAll
                     high-light></tree-transfer>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="transforDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="transforDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!--权限穿梭框-->
    <el-dialog title="关联权限"
               :visible.sync="transforDialog2"
               width="650px"
               :close-on-click-modal="false">
      <el-transfer filterable
                   v-model="selectedRows2"
                   :titles="['全部权限', '已选权限']"
                   :props="{
					key: 'id',
					label: 'name'
				}"
                   :data="permissionList"></el-transfer>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="transforDialog2 = false">取 消</el-button>
        <el-button type="primary"
                   @click="transforDialog2Submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 弹框 -->
    <el-dialog :title="dialogText"
               :close-on-click-modal="false"
               :visible.sync="dialog"
               width="600px">
      <el-form ref="dialogForm"
               :model="dialogForm"
               :rules="rules"
               label-width="130px">
        <el-form-item label="角色名称"
                      prop="name">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="dialogForm.status">
            <el-option label="启用"
                       value="1"></el-option>
            <el-option label="禁用"
                       value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogCancel">取 消</el-button>
        <el-button type="primary"
                   @click="dialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import treeTransfer from 'el-tree-transfer';
import { roleList, addRole, editRole, removeRole, roleMenuList, roleMenu, rolePermissionList, rolePermission } from '@/api/system/role';
import { menuList, permissionList } from '@/api/system/menu';
import { recursion } from '@/utils/recursion';
export default {
  components: { treeTransfer },
  data () {
    return {
      allMenus: [],
      searchForm: {},
      tableData: [],
      dialogText: '新增角色',
      dialog: false,
      mode: 'add',
      menuList: [],
      permissionList: [],
      selectedRows: [],
      selectedRows2: [],
      transforDialog: false,
      transforDialog2: false,
      currentRoleId2: '',
      currentRoleId: '',
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      dialogForm: {
        name: '',
        status: '1'
      },
      pageData: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      }
    };
  },
  mounted () {
    console.info('mounted');
    this.query();
    permissionList().then((res) => {
      if (res.rows && res.rows.length) {
        this.permissionList = res.rows;
      }
    });
  },
  methods: {
    query () {
      let tempObj = {};
      Object.assign(tempObj, this.searchForm);
      tempObj.pageNum = this.pageData.pageNum;
      tempObj.pageSize = this.pageData.pageSize;
      roleList(tempObj).then((res) => {
        this.tableData = res.rows;
        this.pageData.total = res.total;
      });
    },
    treeAdd (leftData, rightData, obj) {
      this.$nextTick(() => {
        obj.nodes.sort((a, b) => a.sort - b.sort);
        let arr = [...obj.nodes];
        let tempArr = [];
        if (obj.halfNodes && obj.halfNodes.length > 0) {
          obj.halfNodes.forEach((e) => {
            let temp = { ...e };
            temp.children = [];
            arr = [temp, ...arr];
          });
        }
        arr.forEach((e) => {
          if (e.parentId != '0') {
            let tempO = arr.find((ee) => ee.id == e.parentId);
            if (tempO) {
              if (!tempO.children.find((ii) => ii.id === e.id)) {
                tempO.children.push(e);
              }
            }
          } else {
            tempArr.push(e);
          }
        });
        if (rightData) {
          tempArr = [...rightData, ...tempArr];
        }
        tempArr = tempArr.sort((a, b) => a.sort - b.sort);
        this.selectedRows = JSON.parse(JSON.stringify(tempArr));
      });
    },
    treeRemove (leftData, rightData, obj) {
      let rData = JSON.parse(JSON.stringify(rightData));
      this.$nextTick(() => {
        let arr = [...leftData];
        if (obj.halfNodes && obj.halfNodes.length > 0) {
          obj.halfNodes.forEach((e) => {
            arr.push(e);
          });
        }
        if (obj.nodes && obj.nodes.length) {
          obj.nodes.forEach((e) => {
            if (e.parentId == '0') {
              // 顶级菜单
              let tempO = arr.find((eee) => e.id == eee.id);
              if (!tempO) arr.push(e);
            } else {
              let tempO = arr.find((ee) => e.parentId == ee.id);
              if (tempO) {
                if (!tempO.children.find((ee) => ee.id == e.id)) {
                  tempO.children.push(e);
                  tempO.children.sort((a, b) => a.sort - b.sort);
                }
              } else {
                arr.push(e);
              }
            }
          });
        }
        arr = arr.sort((a, b) => a.sort - b.sort);
        this.menuList = arr;
        rData.sort((a, b) => a.sort - b.sort);
        this.selectedRows = JSON.parse(JSON.stringify(rData));
      });
    },
    handleSizeChange (value) {
      this.pageData.pageSize = value;
      this.query();
    },
    handleCurrentChange (value) {
      this.pageData.pageNum = value;
      this.query();
    },
    relationMenu (item) {
      this.currentRoleId = item.id;
      roleMenuList({ roleId: item.id }).then((res) => {
        if (res.data && res.data.length) {
          this.selectedRows = res.data;
        } else {
          this.selectedRows = [];
        }
        menuList().then((ress) => {
          if (ress.rows) {
            this.menuList = [];
            ress.rows.forEach((ee) => {
              if (!this.selectedRows.find((i) => i.id == ee.id)) {
                this.$nextTick(() => {
                  this.menuList.push(ee);
                });
              } else {
                let obj = JSON.parse(JSON.stringify(this.selectedRows.find((i) => i.id == ee.id)));
                if (ee.children && ee.children.length && obj.children && obj.children.length) {
                  let tempArr = ee.children.filter((i) => obj.children.find((m) => i.id === m.id) == null);
                  if (tempArr && tempArr.length) {
                    obj.children = tempArr;
                    this.$nextTick(() => {
                      this.menuList.push(obj);
                    });
                  }
                }
              }
            });
          }
        });
        this.transforDialog = true;
      });
    },
    relationPermission (item) {
      this.currentRoleId2 = item.id;
      rolePermissionList({ roleId: item.id }).then((res) => {
        if (res.data && res.data.length) {
          this.selectedRows2 = res.data.map((e) => e.id);
        } else {
          this.selectedRows2 = [];
        }
        this.transforDialog2 = true;
      });
    },
    add () {
      this.dialogForm.id = null;
      this.dialogForm.updateDate = null;
      this.dialogForm.updateId = null;
      this.dialogText = '新增角色';
      this.dialog = true;
      this.mode = 'add';
    },
    edit (item) {
      this.dialogText = '编辑角色';
      this.mode = 'edit';
      this.dialog = true;
      this.$nextTick(() => {
        Object.assign(this.dialogForm, item);
      });
    },
    dialogCancel () {
      this.dialog = false;
      this.$refs['dialogForm'].resetFields();
    },
    dialogSubmit () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          if (this.mode == 'add') {
            let tempObj = {};
            Object.assign(tempObj, this.dialogForm);
            addRole(tempObj).then(() => {
              this.dialog = false;
              this.$message({ message: '新增角色成功', type: 'success' });
              this.$refs['dialogForm'].resetFields();
              this.query();
            });
          } else if (this.mode == 'edit') {
            editRole(this.dialogForm).then(() => {
              this.dialog = false;
              this.$message({ message: '编辑角色成功', type: 'success' });
              this.$refs['dialogForm'].resetFields();
              this.query();
            });
          }
        }
      });
    },
    transforDialogSubmit () {
      roleMenu({ roleId: this.currentRoleId, menusIds: recursion(this.selectedRows).join(',') }).then((res) => {
        if (res.code && res.code === '200') {
          this.transforDialog = false;
          this.$message({ message: '关联菜单成功', type: 'success' });
        }
      });
    },
    transforDialog2Submit () {
      rolePermission({ roleId: this.currentRoleId2, permissionIds: this.selectedRows2.join(',') }).then((res) => {
        if (res.code && res.code === '200') {
          this.transforDialog2 = false;
          this.$message({ message: '关联权限成功', type: 'success' });
        }
      });
    },
    remove (id) {
      this.$confirm('确认要删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeRole(id).then(() => {
          this.$message({ message: '删除用户成功', type: 'success' });
          this.query();
        });
      });
    }
  }
};
</script>
